package com.qf.bo;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.qf.enums.LoginStatusEnum;
import com.qf.util.IpLocationUtils;
import com.qf.util.WebUtils;
import lombok.Builder;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;

/**
 * 登录日志
 *
 * @USER: Administrator
 * @DATE: 2025/9/4 下午10:17
 * @VERSION: 1.0.0
 */
@Data
@Builder
public class LoginLogBO implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 主键ID
     */
    private Long id;

    /**
     * 用户ID（未登录时为NULL）
     */
    private Long userId;

    /**
     * 用户名
     */
    private String username;

    /**
     * 登录时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date loginTime;

    /**
     * 登录IP地址
     */
    private String loginIp;

    /**
     * 用户代理（浏览器/操作系统信息）
     */
    private String userAgent;

    /**
     * 登录状态（1-成功，0-失败）
     */
    private Integer loginStatus;

    /**
     * 失败原因
     */
    private String failReason;

    /**
     * 会话ID
     */
    private String sessionId;

    /**
     * IP归属地
     */
    private String location;

    public static LoginLogBO LoginSuccess(String username, HttpServletRequest request) {
        return LoginLogBO.builder()
                .username(username)
                .loginTime(new Date())
                .loginIp(WebUtils.getIpAddress(request))
                .userAgent(WebUtils.getUserAgent(request))
                .sessionId(WebUtils.getSessionId(request))
                .location(IpLocationUtils.getLocationByIp(WebUtils.getIpAddress(request)))
                .loginStatus(LoginStatusEnum.SUCCESS.getStatus())
                .build();
    }

    public static LoginLogBO LoginFailure(String username,HttpServletRequest request,String failReason) {
        return LoginLogBO.builder()
                .username(username)
                .loginTime(new Date())
                .loginIp(WebUtils.getIpAddress(request))
                .userAgent(WebUtils.getUserAgent(request))
                .sessionId(WebUtils.getSessionId(request))
                .location(IpLocationUtils.getLocationByIp(WebUtils.getIpAddress(request)))
                .loginStatus(LoginStatusEnum.FAILURE.getStatus())
                .failReason(failReason)
                .build();
    }

}
